package es.onlysolutions.gs.web.validator;

import es.onlysolutions.gs.web.commandBean.LoginBean;
import es.onlysolutions.gs.comm.facade.UserFacade;
import es.onlysolutions.gs.comm.entity.User;
import es.onlysolutions.gs.comm.utils.PasswordUtils;
import es.onlysolutions.arq.core.mvc.command.AbstractCommandBean;
import org.springframework.validation.Errors;

/**
 * Validator for the login.
 */
public class LoginValidator extends GSValidator
{

    private UserFacade userFacade;

    public void setUserFacade(UserFacade userFacade)
    {
        this.userFacade = userFacade;
    }

    public boolean supports(Class aClass)
    {
        return LoginBean.class == aClass;
    }

    protected void validateForm(AbstractCommandBean abstractCommandBean, Errors errors)
    {
        LoginBean bean = (LoginBean) abstractCommandBean;

        boolean login = rejectIfEmptyOrWhitespace(errors, "login", "fieldRequired", new String[]{"Login"}, "The field {0} is required");
        boolean password = rejectIfEmptyOrWhitespace(errors, "password", "fieldRequired", new String[]{"Password"}, "The field {0} is required");

        if (login)
        {
            User usuario = userFacade.getUserByLogin(bean.getLogin());
            if (usuario == null)
            {
                errors.rejectValue("login", "login.notExist", new String[]{bean.getLogin()}, "The user with login: {0} do not exist");
            }
            else if (password)
            {
                if (!usuario.getPassword().equals( PasswordUtils.encryptPassword(bean.getPassword()) ) )
                {
                    errors.rejectValue("login", "login.badPassword", "Bad password");
                }
            }
        }
    }
}
